package com.keyancompany.zhongbaopingtai.activity;

import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.api.TeamAPI;
import com.keyancompany.zhongbaopingtai.api.UserAPI;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.EventBusEntity;
import com.keyancompany.zhongbaopingtai.model.User;
import com.keyancompany.zhongbaopingtai.utils.DateUtils;
import com.keyancompany.zhongbaopingtai.utils.IntentUtils;
import com.keyancompany.zhongbaopingtai.utils.T;
import com.keyancompany.zhongbaopingtai.weight.DatePopupWindow;
import com.keyancompany.zhongbaopingtai.weight.MenuPopuWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.Bind;
import butterknife.BindString;
import butterknife.OnClick;

/**
 * @author firefox
 *         新建任务
 */
public class CreateTaskActivity extends BaseActivity {

    @BindString(R.string.create_task)
    String title;

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.task_header)
    EditText taskHeader;
    @Bind(R.id.task_tag)
    EditText taskTag;
    @Bind(R.id.assign_member)
    TextView assignMember;
    @Bind(R.id.priority)
    Spinner priority;
    @Bind(R.id.planned_start_time)
    TextView plannedStartTime;
    @Bind(R.id.planned_completion_time)
    TextView plannedCompletionTime;
    @Bind(R.id.task_describe)
    EditText taskDescribe;
    @Bind(R.id.txt_create)
    TextView txtCreate;

    private DatePopupWindow datePopupWindow;
    private int currentPriority = 0;
    private String teamCode;
    private String toUser;
    private String startTime;
    private String endTime;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_create_task;
    }

    @Override
    protected int getMenuId() {
        return 0;
    }

    @Override
    protected void initToolBar() {
        initToolBar(toolbar, title);
    }

    @Override
    protected void setUpViews() {
        EventBus.getDefault().register(this);
        teamCode = getIntent().getStringExtra(Constants.TEAM_CODE);
        // 建立数据源
        String[] mItems = getResources().getStringArray(R.array.level_arrays);
        // 建立Adapter并且绑定数据源
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mItems);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //绑定 Adapter到控件
        priority.setAdapter(adapter);

        priority.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

                currentPriority = pos;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });


    }

    @OnClick(R.id.txt_create)
    void createTask() {

    }

    @OnClick(R.id.planned_start_time)
    void setPlannedStartTime(View view) {

        if (datePopupWindow == null) {
            datePopupWindow = new DatePopupWindow(mContext);
        }
        datePopupWindow.setDateListener(new DatePopupWindow.IOnSelectDateListener() {
            @Override
            public void selectDate(int year, int moth, int day) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(year, moth, day);
                plannedStartTime.setText(DateUtils.formatDate(calendar.getTime()));
                startTime = DateUtils.formatDate(calendar.getTime());
            }
        });
        datePopupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    @OnClick(R.id.planned_completion_time)
    void setPlannedCompletionTime(View view) {

        if (datePopupWindow == null) {
            datePopupWindow = new DatePopupWindow(mContext);
        }
        datePopupWindow.setDateListener(new DatePopupWindow.IOnSelectDateListener() {
            @Override
            public void selectDate(int year, int moth, int day) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(year, moth, day);
                plannedCompletionTime.setText(DateUtils.formatDate(calendar.getTime()));
                endTime = DateUtils.formatDate(calendar.getTime());
            }
        });
        datePopupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }


    @OnClick(R.id.txt_create)
    void createTask(View view) {
        String taskHeaderTxt = taskHeader.getText().toString();
        if (TextUtils.isEmpty(taskHeaderTxt)) {
            T.showShort(this, "请输入任务标题");
            return;
        }
        String taskTagTxt = taskTag.getText().toString();
        if (TextUtils.isEmpty(taskTagTxt)) {
            T.showShort(this, "请输入任务标签");
            return;
        }
        String assignMemberTxt = assignMember.getText().toString();
        if (TextUtils.isEmpty(assignMemberTxt) || assignMember.getTag() == null) {
            T.showShort(this, "请选择指派成员");
            return;
        }
        String plannedStartTimeTxt = plannedStartTime.getText().toString();
        if (TextUtils.isEmpty(plannedStartTimeTxt)) {
            T.showShort(this, "请输入计划开始时间");
            return;
        }

        String plannedCompletionTimeTxt = plannedCompletionTime.getText().toString();
        if (TextUtils.isEmpty(plannedCompletionTimeTxt)) {
            T.showShort(this, "请输入计划完成时间");
            return;
        }
        String taskDescribeTxt = taskDescribe.getText().toString();
        if (TextUtils.isEmpty(taskDescribeTxt)) {
            T.showShort(this, "请输入任务描述");
            return;
        }
        TeamAPI.saveTask(teamCode, taskHeaderTxt, taskDescribeTxt, toUser, currentPriority + "",
                UserAPI.getUserId(), plannedStartTimeTxt, plannedCompletionTimeTxt, taskTagTxt, this, getLoading(R.string.watting_hint));
    }

    @Override
    public void success(int type, String json) {
        super.success(type, json);
        BaseModel base = validateJson(json);
        if (base == null) return;
        if (base.isSuccess()) {
            finish();
        }
        T.showShort(mContext, base.msg);
    }

    @OnClick(R.id.assign_member)
    void assignMember(View view) {
        IntentUtils.startActivity(this, MemberActivity.class, Constants.TEAM_CODE, teamCode);
    }

    /**
     * 事件订阅者自定义的接收方法
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
//        //（1）将事件发布者发布的数据作为文本修改内容
//        msgFragment.setText(event.data);
        //（2）将事件发布者发布的数据作为方法执行的区分
        switch (event.getType()) {
            case EventBusEntity.Type.CHOOSE_ITEM:
                User item = (User) event.getItem();
                assignMember.setText(item.getUsername());
                assignMember.setTag(item.getUserCode());
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
